# -*- coding: utf-8 -*-
import socketserver
import _thread
import time
import logging
from base.Helper import Helper
from logger.Logger import Logger


class CommServer(socketserver.BaseRequestHandler):
    tcp_data = ""

    def handle(self):
        """
        有连接上来的时候，将触发这个处理
        :return:
        """
        conn = self.request
        while True:
            try:
                ret_bytes = conn.recv(1024 * 2)
                ret_str = str(ret_bytes, encoding="utf-8")
                tcp_data = ret_str
                # 通讯建立后创建线程
                _thread.start_new_thread(self.task, (conn, ret_str))
            except OSError as e:
                break
            time.sleep(0.1)

    # 线程
    def task(self, conn, data):
        if data:
            try:
                while True:
                    # 这里可以写自己的业务逻辑

                    time.sleep(5)
            except IndexError as e:
                Logger('error.log', level='info').logger.info(e)


if __name__ == "__main__":
    print('*' * 50)
    print('深圳市咪码科技有限公司')
    print('Comm Server v1.0')
    print('2020年5月27日')
    print('*' * 50)

    logging.basicConfig(format='【%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s:%(message)s】',
                        level=logging.INFO)

    # ip = str(Config.getConfig('service', 'ip'))
    # port = int(Config.getConfig('service', 'port'))
    ip = '127.0.0.1'
    port = 11931

    Helper.killPort(port)

    logging.info('服务开启>>>地址>>>' + ip + '>>>端口号>>>' + str(port))
    server = socketserver.ThreadingTCPServer((ip, port), CommServer)
    server.serve_forever()
